package com.example.smartcity.ui.frg

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.smartcity.R
import com.example.smartcity.adapter.SellerGridAdapter
import com.example.smartcity.adapter.SellerListAdapter
import com.example.smartcity.adapter.TOFThemeGridAdapter
import com.example.smartcity.app.App
import com.example.smartcity.http.AdvBannerBean
import com.example.smartcity.http.AdvBannerResp
import com.example.smartcity.http.SellerListResp
import com.example.smartcity.http.ThemeResp
import com.example.smartcity.ui.act.TOFSearchResultActivity
import com.example.smartcity.ui.act.TOFSellerDetailActivity
import com.example.smartcity.ui.act.TOFSellerListActivity
import com.example.smartcity.utils.CommonUtil
import com.example.smartcity.utils.KeyboardUtil
import com.lljjcoder.Interface.OnCityItemClickListener
import com.lljjcoder.bean.CityBean
import com.lljjcoder.bean.DistrictBean
import com.lljjcoder.bean.ProvinceBean
import com.lljjcoder.citywheel.CityConfig
import com.lljjcoder.style.citylist.Toast.ToastUtils
import com.lljjcoder.style.citypickerview.CityPickerView
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.indicator.CircleIndicator
import kotlinx.android.synthetic.main.fragment_tof_tab1.*
import kotlinx.android.synthetic.main.layout_app_bar_common.*


/**
 * @Author: Tailyou(祝文飞)
 * @CreateDate: 2021/10/7 14:53
 * @Description: 主页
 */
class TOFTabFrg1 : Fragment(R.layout.fragment_tof_tab1) {

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initUI()
        loadBannerData()
        loadThemeData()
        loadRecommendSellerData()
        loadNearbySellerData()
    }

    private fun initUI() {
        tvAppBarTitle.text = "外卖点餐"
        ivAppBarLeft.setOnClickListener { activity?.finish() }
        tvCity.setOnClickListener {
            val mPicker = initCityPicker()
            mPicker.showCityPicker()
        }
        edtSearch.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                var keyword = edtSearch.text.toString()
                if (keyword.isBlank()) {
                    CommonUtil.showToast(requireActivity(), edtSearch.hint.toString())
                } else {
                    doSearch(keyword)
                }
                KeyboardUtil.hideKeyboard(edtSearch.windowToken, context)
                true
            }
            false
        }
    }

    // 执行搜索
    private fun doSearch(keyword: String) {
        App.fetchData<String>(
            "/prod-api/api/takeout/search?keyword=$keyword",
            String::class.java
        ) {
            edtSearch.text?.clear()
            val intent = Intent(activity, TOFSearchResultActivity::class.java)
            intent.putExtra("search_result", it)
            startActivity(intent)
        }
    }

    // 初始化城市选择器
    private fun initCityPicker(): CityPickerView {
        val mPicker = CityPickerView()
        mPicker.init(activity)
        val cityConfig = CityConfig.Builder().build()
        mPicker.setConfig(cityConfig)
        mPicker.setOnCityItemClickListener(object : OnCityItemClickListener() {
            override fun onSelected(
                province: ProvinceBean?,
                city: CityBean?,
                district: DistrictBean?
            ) {
                tvCity.text = city?.name
            }

            override fun onCancel() {
                ToastUtils.showLongToast(activity, "已取消")
            }
        })
        return mPicker
    }

    // 读取附近店铺数据
    private fun loadNearbySellerData() {
        App.fetchData<SellerListResp>(
            "/prod-api/api/takeout/seller/near",
            SellerListResp::class.java
        ) { renderNearbySellerData(it) }
    }

    // 渲染附近店铺数据
    private fun renderNearbySellerData(sellerListResp: SellerListResp) {
        val linearLayoutManager = LinearLayoutManager(activity)
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        rvSellerNearby.layoutManager = linearLayoutManager
        rvSellerNearby.adapter = SellerListAdapter(sellerListResp.rows,
            object : SellerListAdapter.OnItemClickListener {
                override fun onClick(position: Int) {
                    val intent =
                        Intent(activity, TOFSellerDetailActivity::class.java)
                    intent.putExtra("seller_id", sellerListResp.rows[position].id)
                    startActivity(intent)
                }
            })
    }

    // 读取推荐店铺数据
    private fun loadRecommendSellerData() {
        App.fetchData<SellerListResp>(
            "/prod-api/api/takeout/seller/list?recommend=Y",
            SellerListResp::class.java
        ) { renderRecommendSellerData(it) }
    }

    // 渲染推荐店铺数据
    private fun renderRecommendSellerData(sellerListResp: SellerListResp) {
        rvSellerGrid.layoutManager = GridLayoutManager(context, 2)
        rvSellerGrid.adapter = SellerGridAdapter(sellerListResp.rows,
            object : SellerGridAdapter.OnItemClickListener {
                override fun onClick(position: Int) {
                    val intent =
                        Intent(activity, TOFSellerDetailActivity::class.java)
                    intent.putExtra("seller_id", sellerListResp.rows[position].id)
                    startActivity(intent)
                }
            })
    }

    // 读取外卖分类数据
    private fun loadThemeData() {
        App.fetchData<ThemeResp>(
            "/prod-api/api/takeout/theme/list",
            ThemeResp::class.java
        ) { renderThemeData(it) }
    }

    // 渲染外卖分类数据
    private fun renderThemeData(themeResp: ThemeResp) {
        rvThemeGrid.layoutManager = GridLayoutManager(context, 5)
        rvThemeGrid.adapter =
            TOFThemeGridAdapter(themeResp.data, object : TOFThemeGridAdapter.OnItemClickListener {
                override fun onClick(position: Int) {
                    val intent = Intent(context, TOFSellerListActivity::class.java)
                    intent.putExtra("theme_id", themeResp.data[position].id)
                    startActivity(intent)
                }
            })
    }

    // 读取广告Banner数据
    private fun loadBannerData() {
        App.fetchData<AdvBannerResp>(
            "/prod-api/api/takeout/rotation/list",
            AdvBannerResp::class.java
        ) { renderBannerData(it) }
    }

    // 渲染Banner数据
    private fun renderBannerData(data: AdvBannerResp) {
        banner.addBannerLifecycleObserver(this@TOFTabFrg1)
        banner.indicator = CircleIndicator(context)
        banner.adapter =
            object : BannerImageAdapter<AdvBannerBean>(data.rows) {
                override fun onBindView(
                    p0: BannerImageHolder?,
                    p1: AdvBannerBean?,
                    p2: Int,
                    p3: Int
                ) {
                    App.fetchRCImage(
                        p1?.advImg,
                        p0!!.imageView,
                        error = R.mipmap.ic_more_service
                    )
                    p0!!.imageView.setOnClickListener {
                        val intent = Intent(context, TOFSellerDetailActivity::class.java)
                        intent.putExtra("seller_id", p1?.targetId)
                        startActivity(intent)
                    }
                }
            }
    }

}